#-*- coding:utf-8 -*-
import os
import sys
import shutil
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from asset_widget.project_submit_widget import ProjectListWidget
from asset_widget.progressBar_widget import MyProgressBar
from asset_widget.AssetDB import AssetDB


class CopyThread(QThread):
    def __init__(self,origin_des_path_tuple_list):#传原始路径列表过来
        '''
        创建时就获取到对应的list
        :param origin_des_path_tuple_list: eg[(origin_path1,des_path1),(origin_path2,des_path2)...]
        '''
        super(CopyThread,self).__init__()
        self.path_list=origin_des_path_tuple_list



    def run(self):
        for i in self.path_list:
            if os.path.isfile(i[0]):
                shutil.copyfile(i[0],i[1])
            elif os.path.isdir(i[0]):
                shutil.copytree(i[0],i[1])
            else:
                pass




class Upload(QWidget):

    def __init__(self):
        super(Upload,self).__init__()

        self.setStyleSheet('background-color:rgb(75,75,75);color:rgb(220,220,220)')
        #全局变量
        self.submit_path='//192.168.1.247/effects/AssetsLib'#工程存放路径
        self.des_dir_path='' #最终提交的项目路径
        self.path_list=[]#提交的项目原路径列表，从提交列表处实时刷新
        self.origin_count=0#原提交的文件或文件夹数量
        #数据库
        self.db_path=os.path.join(self.submit_path,'db')
        self.db=AssetDB(self.db_path,'asset_lib')


        self.setWindowTitle('上传资产')
        self.mainLayout=QHBoxLayout()
        self.mainLayout.setContentsMargins(20,20,20,20)

        self.left_layout=QVBoxLayout()
        self.asset_label=QLabel('资产上传列表:')
        self.asset_list_widget=ProjectListWidget()
        self.asset_list_widget.path_list_Signal.connect(self.__resetPathList)
        self.left_layout.addWidget(self.asset_label)
        self.left_layout.addWidget(self.asset_list_widget)

        self.right_layout=QVBoxLayout()
        self.asset_name_layout=QHBoxLayout()
        self.asset_name_label=QLabel('资产名称:')
        self.asset_name_edit=QLineEdit()
        self.asset_name_layout.addWidget(self.asset_name_label)
        self.asset_name_layout.addWidget(self.asset_name_edit)

        self.comment_layout=QHBoxLayout()
        self.comment_label=QLabel('资产说明:')
        self.content_text=QTextEdit()
        self.comment_layout.addWidget(self.comment_label)
        self.comment_layout.addWidget(self.content_text)

        self.tag_layout=QHBoxLayout()
        self.tag_label=QLabel('资产标签:')
        self.tag_edit=QLineEdit()
        self.tag_edit.setPlaceholderText("以空格分开")
        self.tag_layout.addWidget(self.tag_label)
        self.tag_layout.addWidget(self.tag_edit)

        self.name_layout=QHBoxLayout()
        self.name_label=QLabel('上传人员:')
        self.name_edit=QLineEdit()
        self.name_layout.addWidget(self.name_label)
        self.name_layout.addWidget(self.name_edit)

        self.btn_layout=QHBoxLayout()
        self.OK_btn=QPushButton('上传')
        self.OK_btn.clicked.connect(self.__upload)
        self.OK_btn.setMinimumSize(50,50)
        self.NO_btn=QPushButton('取消')
        self.NO_btn.setMinimumSize(50, 50)
        self.NO_btn.clicked.connect(self.__closeWindow)
        self.btn_layout.addWidget(self.OK_btn)
        self.btn_layout.addWidget(self.NO_btn)

        self.right_layout.addLayout(self.asset_name_layout)
        self.right_layout.addLayout(self.comment_layout)
        self.right_layout.addLayout(self.tag_layout)
        self.right_layout.addLayout(self.name_layout)
        self.right_layout.addLayout(self.btn_layout)


        self.mainLayout.addLayout(self.left_layout)
        self.mainLayout.addLayout(self.right_layout)


        self.setLayout(self.mainLayout)

        #计时器
        self.timer=QBasicTimer()
        #进度条
        self.p=MyProgressBar()


    def __upload(self):
        if self.path_list ==[]:
            QMessageBox.information(self,'提示','请拖入项目工程文件或目录')
        else:
            if self.asset_name_edit.text() and self.content_text.toPlainText() and self.tag_edit.text() and self.name_edit.text():


                asset_name=self.asset_name_edit.text()
                content=self.content_text.toPlainText()
                tag=self.tag_edit.text()
                tag_list=tag.split(' ')
                lass_tag_list=[i for i in tag_list if i is not '']
                name=self.name_edit.text()

                project_list=os.listdir(self.submit_path)
                count=len(project_list)
                real_asset_name=asset_name+str(count)
                self.des_dir_path=os.path.join(self.submit_path,real_asset_name)#最终路径
                os.makedirs(self.des_dir_path)
            #写入信息
                info={}
                info['asset_name']=real_asset_name
                info['content']=content
                info['tag']=lass_tag_list
                info['name']=name
                info['asset_path']=self.des_dir_path

                info_path=os.path.join(self.des_dir_path,'info')
                self.__writeInfo(info_path,info)

            #存数据库
                self.db.addData(info)
            #获取路径组列表
                temp_tuple_list=self.__get_path_tuple_list(self.des_dir_path)

                self.p.show()
                self.__threadOn(temp_tuple_list)#进行读条

            else:
                QMessageBox.information(self,'提示','请输入完整信息')


    def __writeInfo(self,path,data):
        with open(path,'w',encoding='utf-8') as w:
            w.write(str(data))


    def __get_path_tuple_list(self,tar_project_path):
        temp_tuple_list=[]
        for i in self.path_list:
            path_trail=os.path.split(i)[1]
            tar_path=os.path.join(tar_project_path,path_trail)
            temp_tuple=(i,tar_path)
            temp_tuple_list.append(temp_tuple)

        return temp_tuple_list

    def __resetPathList(self,path_list):
        '''
        槽函数，从上传列表中传过来
        :param path_list:
        :return:
        '''
        self.path_list=path_list
        self.origin_count=len(self.path_list)#因为有一个info文件
        print(self.origin_count)

    def timerEvent(self, *args, **kwargs):
        if self.des_dir_path !='':
            current_count=len(os.listdir(self.des_dir_path))
            delta=self.origin_count-current_count
            value=100-((delta)*100.0/self.origin_count)
            self.p.setValue(value)
            if value==100:
                self.p.close()
                self.timer.stop()
                QMessageBox.information(self,'提示','上传完成')
                self.close()


    def __threadOn(self,temp_tuple_list):
        self.timer.start(10,self)
        self.work=CopyThread(temp_tuple_list)
        self.work.start()




    def __closeWindow(self):
        self.close()


if __name__ == '__main__':
    app=QApplication()
    up=Upload()
    up.show()
    sys.exit(app.exec_())